const app = getApp();
import Dialog from '@vant/weapp/dialog/dialog';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    app,
    reportValue:'',//举报内容
    reportDialog:false,
    reportShow:false,
    reportListShow:false,
    login:false,//是否登录
    onFoldShow:false,
    onFold: false,
    btnText:'',
    work_id:'',
    report:[
      {
        name: '我要举报',
      }
    ],
    reportList:[
      {
        name:"滥发广告",
        value:1,
      },
      {
        name:"违规信息",
        value:2,
      },
      {
        name:"虚假交换",
        value:3,
      },
      {
        name:"涉嫌抄袭",
        value:4,
      },
      {
        name:"重复交稿",
        value:5,
      },
      {
        name:"其他",
        value:6,
      },
    ],
    photoSelect:[
      {
        name:'下载图片',
        value:1,
      },
      {
        name:'预览图片',
        value:2,
      }
    ],
    photoSelectShow:false,
    photoUrl:'',
    btnFunName:'',
    collectionBool:false,
    uid:'',
    id:'',
    seeMoreType:false,
    taskContributeList:'',
    taskContributeNum:'0',
    deliverManuscriptList:'',
    protectionList:'',
    taskDetail:'',
    reportType:'',
    myInfo:'',
    beforeClose(action) {
      return new Promise((resolve) => {
        setTimeout(() => {
          if (action === 'confirm') {
            // 拦截确认操作
            resolve(false);
          } else {
            resolve(true);
          }
        }, 0);
      });
    }
  },





  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let uid=wx.getStorageSync('uid')
    this.setData({
      id:options.id,
      uid,
    })



    // 投稿数量
    this.taskContributeNum();

    // this.checkFold()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 任务详情信息
    this.taskDetail();
    this.taskContributeNum();
    // 投稿记录
    this.taskContributeList();
    if (app.globalData.token) {
      this.setData({
        login:true
      })
      // 交稿记录
      this.deliverManuscript();
      // 维权列表
      this.protectionList();
      // 评论列表
      this.commentList();
    }
  },

  //qu登录
  goLogin(){
    wx.navigateTo({
      url: '/taskPage/pages/taskContribute/taskContribute?id=' + id + '&taskType=' + taskDetail.task_type,
    })
  },

  optionHand(){
    if(this.data.btnFunName){
      this[this.data.btnFunName]()
    }
  },

  collection(){
    if(this.data.taskDetail.focused){
      this.delCollectBtn()
    }else {
      this.collectBtn()
    }
  },



  onClose() {
    this.setData({ reportShow: false });
  },
  onSelect(event) {
    if(event.detail.name==="我要举报"){
          this.setData({reportListShow:true})
    }
  },

  openReport(e){
    const {work_id}=e.currentTarget.dataset
    this.setData({
      reportShow: true,
      work_id
    });
  },

  onCloseReportList(){
    this.setData({reportListShow:false})
  },

  onSelectReportList(event){
    this.setData({
      reportDialog:true,
      reportType:event.detail.value,
    })
  },

  onCloseDialog(){
    this.setData({
      reportDialog:false,
      reportValue:'',
    })
  },


  /**
   * 举报
   */
  reportInto() {
    let _this=this
    let id = this.data.taskDetail.id
    const {work_id,reportValue,reportType}=this.data
    if(!reportValue){
      wx.showToast({
        title: '请填写违规内容',
        icon: 'none',
        duration: 2000
      })
      return false
    }
  /*  wx.showLoading({
      title: '加载中',
    })*/
    wx.request({
      url: app.globalData.baseUrl + 'task/report',
      data: {
        type:reportType,
        task_id: id,
        work_id: work_id,
        token: app.globalData.token,
        desc:reportValue
      },
      method:'POST',
      header:{
        'content-type':'application/x-www-form-urlencoded'
      },
      success(res) {
        wx.hideLoading()
        _this.onCloseDialog();
        if (res.data.code == 1000) {
          wx.showToast({
            title: '谢谢您的反馈，平台将尽快处理',
            icon: 'none',
            duration: 2000
          })
          setTimeout(function(){
            _this.taskDetail();
          },2000)
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },

  //文字收起打开
  checkFold(){
    let query = wx.createSelectorQuery();
    query.select('.info-text-box').boundingClientRect()
    query.select('.info-text').boundingClientRect()
    query.exec(res=>{

      const [ fixedElement, emptyElement ] = res;
      let data=emptyElement.height>fixedElement.height
      this.setData({onFoldShow:data})
    })
  },

  changeFold(){
    this.setData({onFold:!this.data.onFold})
  },


  // 底部列表切换
  taskTabBtn:function(e){
    var { index } = e.currentTarget.dataset
    this.setData({
      taskTabType: index
    })
  },
  // 展开收起
  seeMoreBtn:function(){
    var { seeMoreType } = this.data;
    this.setData({
      seeMoreType: !seeMoreType
    })
  },
  // 联系
  contactBtn:function(){
    wx.showToast({
      title: '请前往pc端im工具联系对方',
      icon: 'none',
      duration: 2000
    })
    /*var { taskDetail } = this.data;
    wx.makePhoneCall({
      phoneNumber: taskDetail.phone
    })*/
  },


  /**
   * 关注发布者
   */
  userFocus(){
    if(app.globalData.token){
      let _this=this
      wx.showLoading({
        title: '加载中',
      })
      wx.request({
        url: app.globalData.baseUrl + 'task/focusUser',
        data: {
          focus_uid: _this.data.taskDetail.uid,
          token: app.globalData.token
        },
        success(res) {
          wx.hideLoading()
          if (res.data.code == 1000) {
            wx.showToast({
              title: '关注成功',
              icon: 'success',
              duration: 2000
            })
            setTimeout(function () {
              _this.taskDetail();
            }, 2000)
          } else {
            wx.showToast({
              title: res.data.message,
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    }else {
      wx.showModal({
        title: '提示',
        content: '您未登录，是否去登陆？',
        success(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/userPage/pages/login/login',
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }

  },

  // 收藏
  collectBtn:function(e){
    var id = this.data.taskDetail.id
    var _this = this;
    if (!app.globalData.token) {
      wx.showModal({
        title: '提示',
        content: '您未登录，是否去登陆？',
        success(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/userPage/pages/login/login',
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: app.globalData.baseUrl + 'user/addFocus',
      data: {
        task_id: id,
        token: app.globalData.token
      },
      success(res) {
        wx.hideLoading()
        if (res.data.code == 1000) {
          wx.showToast({
            title: '收藏成功',
            icon: 'success',
            duration: 2000
          })
          setTimeout(function(){
            _this.taskDetail();
          },2000)
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  // 取消收藏
  delCollectBtn:function(e){
    var id  = this.data.taskDetail.id
    var _this = this;
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: app.globalData.baseUrl + 'user/deleteFocus',
      data: {
        id: id,
        token: app.globalData.token
      },
      method:'POST',
      header:{
        'content-type':'application/x-www-form-urlencoded'
      },
      success(res) {
        wx.hideLoading()
        console.log(res)
        if (res.data.code == 1000) {
          wx.showToast({
            title: '取消成功',
            icon: 'success',
            duration: 2000
          })
          setTimeout(function () {
            _this.taskDetail();
          }, 2000)
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  // 任务详情信息
  taskDetail:function(){
    var _this = this;
    var { id } = this.data;
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: app.globalData.baseUrl + 'myTask/detail',
      data: {
        id:id,
        token: app.globalData.token
      },
      success(res) {
        wx.hideLoading()
        if (res.data.code == 1000) {
          _this.btnChange(res.data.data)
          _this.setData({
            taskDetail:res.data.data
          })
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },


  btnChange(data){
    let _this=this
    if(data.role== 'employee'){
        _this.setData({
          btnText:data.employee_button_desc,
        })
        switch (data.employee_button){
          case 0:
            _this.setData({
              btnFunName:'loginBtn',
            })
            break;
          case 1:
            _this.setData({
              btnFunName:'taskContribute',
            })
            break;
          case 6:
            _this.setData({
              btnFunName:'wkConfirmPayType',
            })
            break;
          case 7:
            _this.setData({
              btnFunName:'submitManuscript',
            })
            break;

          case 10:
            _this.setData({
              btnFunName:'taskEvaluation',
            })
            break;
          case 13:
            _this.setData({
              btnFunName:'orderDetail',
            })
            break;
          default:
            _this.setData({
              btnFunName:'',
            })

        }
    }
    if(data.role== 'employer'){
      _this.setData({
        btnText:data.employer_button_desc,
      })
        switch (data.employer_button){
          case 4:
            _this.setData({
              btnFunName:'taskEscrowAmount',
            })
            break;
          case 5:
            _this.setData({
              btnFunName:'employerPayType',
            })
            break;
          case 13:
            _this.setData({
              btnFunName:'orderDetail',
            })
            break;
          default:
            _this.setData({
              btnFunName:'',
            })
        }
    }
    if(data.role == 'visitor'){
      _this.setData({
        btnText:"请先登录",
        btnFunName:'loginBtn',
      })
    }
  },



  // 我有投稿
  taskContribute:function(){
    var { id, taskDetail } = this.data;
    if(!app.globalData.token){
      wx.showToast({
        title: '您还未登录',
        icon: 'none',
        duration: 2000
      })
    }
    wx.navigateTo({
      url: '/taskPage/pages/taskContribute/taskContribute?id=' + id + '&taskType=' + taskDetail.task_type,
    })
  },
  // 投稿记录
  taskContributeList:function(){
    var _this = this
    var url = app.globalData.baseUrl + 'task/deliveryLists';
    var { id } = this.data;
    var data = {
      id: id,
      token: app.globalData.token
    }
    wx.showLoading({
      title: '加载中',
    })
    app.wxGetRequest(url, data,(res) =>{
      wx.hideLoading()
      console.log(res)
      if (res.code == 1000){
        _this.setData({
          taskContributeList: res.data
        })
      }
    }, (err) =>{
      wx.hideLoading()
      wx.showToast({
        title: err.data.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  // 投稿记录数量
  taskContributeNum:function(){
    var _this = this
    var url = app.globalData.baseUrl + 'task/getDeliveryListsCount';
    var { id } = this.data;
    var data = {
      id: id
    }
    app.wxGetRequest(url, data, (res) => {
      if (res.code == 1000) {
        _this.setData({
          taskContributeNum: res.data.count
        })
      }
    }, (err) => {
      wx.showToast({
        title: err.data.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  // 雇主选择稿件
  selectedTa:function(e){
    let { id, name} = e.currentTarget.dataset
    Dialog.confirm({
      title: '审核提示',
      message: '确定将'+name+'设置为中标吗？',
    })
        .then(() => {
            this.winBid(id)
        })
        .catch(() => {

        });
  },

  winBid(id){
    var _this = this
    var url = app.globalData.baseUrl + 'work/winBid';
    var data = {
      id: id,
      token: app.globalData.token
    }
    app.wxGetRequest(url, data, (res) => {
      if (res.code == 1000) {
        wx.showToast({
          title: '选稿成功',
          icon: 'success',
          duration: 2000
        })
        setTimeout(function(){
          _this.taskDetail();
          _this.taskContributeList();
        },2000)
      }
    }, (err) => {
      wx.showToast({
        title: err.data.message,
        icon: 'none',
        duration: 2000
      })
    })
  },



  // 交稿记录
  deliverManuscript:function(){
    var _this = this
    var url = app.globalData.baseUrl + 'task/deliveryList';
    var { id } = this.data;
    var data = {
      id: id,
      token: app.globalData.token
    }
    wx.showLoading({
      title: '加载中',
    })
    app.wxGetRequest(url, data, (res) => {
      wx.hideLoading()
      if (res.code == 1000) {
        _this.setData({
          deliverManuscriptList: res.data
        })
      }
    }, (err) => {
      wx.hideLoading()
      wx.showToast({
        title: err.data.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  // 维权列表
  protectionList: function () {
    var _this = this
    var url = app.globalData.baseUrl + 'task/rightList';
    var { id } = this.data;
    var data = {
      id: id,
      token: app.globalData.token
    }
    wx.showLoading({
      title: '加载中',
    })
    app.wxGetRequest(url, data, (res) => {
      console.log(res)
      wx.hideLoading()
      if (res.code == 1000) {
        _this.setData({
          protectionList: res.data
        })
      }
    }, (err) => {
      wx.hideLoading()
      wx.showToast({
        title: err.data.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  // 评论列表
  commentList: function () {
    var _this = this
    var url = app.globalData.baseUrl + 'task/commentList';
    var { id } = this.data;
    var data = {
      id: id,
      token: app.globalData.token
    }
    wx.showLoading({
      title: '加载中',
    })
    app.wxGetRequest(url, data, (res) => {
      console.log(res)
      wx.hideLoading()
      if (res.code == 1000) {
        _this.setData({
          commentList: res.data
        })
      }
    }, (err) => {
      wx.hideLoading()
      wx.showToast({
        title: err.data.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  // 托管赏金
  taskEscrowAmount:function(){
    var { id, taskDetail, taskContributeList } = this.data;
    var servicePrice = 0;
    for (var i = 0; i < taskContributeList.workList.length; i++){
      if (taskContributeList.workList[i].status == 1){
        servicePrice = taskContributeList.workList[i].price
      }
    }
    var url = app.globalData.baseUrl + 'pay/orderInfo';
    // 获取订单号
    var data = {
      task_id: id,
      token: app.globalData.token
    }
    wx.showLoading({
      title: '正在创建订单',
    })
    app.wxGetRequest(url, data, (orderRes) => {
      console.log(orderRes)
      wx.hideLoading()
      if (orderRes.code == 1000) {
        wx.navigateTo({
          url: '/taskPage/pages/pay/pay?taskid=' + id + '&title=' + taskDetail.title + '&servicePrice=' + servicePrice + '&code=' + orderRes.data.code,
        })
      }else{
        wx.showToast({
          title: orderRes.message,
          icon: 'none',
          duration: 2000
        })
      }
    }, (err) => {
      wx.hideLoading()
      wx.showToast({
        title: err.data.message,
        icon: 'none',
        duration: 2000
      })
    })
    // wx.navigateTo({
    //   url: '/taskPage/pages/pay/pay?taskid=' + id + '&title=' + taskDetail.title + '&servicePrice=' + servicePrice,
    // })
  },
  // 雇主设置付款方式
  employerPayType:function(){
    var { id, taskContributeList, taskDetail } = this.data;
    var servicePrice = 0;
    for (var i = 0; i < taskContributeList.workList.length; i++) {
      if (taskContributeList.workList[i].status == 1) {
        servicePrice = taskContributeList.workList[i].price
      }
    }
    wx.navigateTo({
      url: '/pages/payMethod/payMethod?taskid=' + id + '&servicePrice=' + servicePrice + '&paytypeStatus=' + taskDetail.employer_paytype_status,
    })
  },
  // 威客确认支付方式
  wkConfirmPayType:function(){
    var { id, taskContributeList, taskDetail } = this.data;
    var servicePrice = 0;
    for (var i = 0; i < taskContributeList.workList.length; i++) {
      if (taskContributeList.workList[i].status == 1) {
        servicePrice = taskContributeList.workList[i].price
      }
    }
    wx.navigateTo({
      url: '/pages/payMethod/payMethod?taskid=' + id + '&servicePrice=' + servicePrice,
    })
  },
  // 威客交稿
  submitManuscript:function(){
    var { deliverManuscriptList, taskDetail } = this.data
    var jd = '';
    if (taskDetail.task_type != 'xuanshang'){
      if (deliverManuscriptList == '') {
        jd = 1
      } else {
        if (deliverManuscriptList[deliverManuscriptList.length - 1].status == 3) {
          jd = deliverManuscriptList.length + 1
        } else {
          jd = deliverManuscriptList.length
        }
      }
    }
    var { id } = this.data
    wx.navigateTo({
      url: '/taskPage/pages/submitTaskManuscript/submitTaskManuscript?id=' + id + '&jd=' + jd,
    })
  },
  // 验收
  acceptanceBtn:function(e){
    var _this = this
    var url = app.globalData.baseUrl + 'work/deliveryAgree';
    var data = {
      work_id: e.currentTarget.dataset.id,
      status: e.currentTarget.dataset.type,
      token: app.globalData.token
    }
    wx.showLoading({
      title: '加载中',
    })
    app.wxGetRequest(url, data, (res) => {
      console.log(res)
      wx.hideLoading()
      if (res.code == 1000) {
        wx.showToast({
          title: '提交成功',
          icon: 'success',
          duration: 2000
        })
        setTimeout(function () {
          _this.taskDetail();
          _this.deliverManuscript();
        }, 2000)
      }
    }, (err) => {
      wx.hideLoading()
      wx.showToast({
        title: err.data.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  // 维权
  protectionBtn:function(e){
    var { workid } = e.currentTarget.dataset
    var { id } = this.data
    wx.navigateTo({
      url: '/taskPage/pages/protection/protection?taskid=' + id + '&workid=' + workid,
    })
  },
  // 评价
  taskEvaluation:function(e){
    console.log(e)
    var { type } = e.currentTarget.dataset
    var { id, taskContributeList, taskDetail } = this.data
    var workid = ''
    if(type==2){
      var { index } = e.currentTarget.dataset
      var { deliverManuscriptList } = this.data
      wx.navigateTo({
        url: '/taskPage/pages/taskEvaluation/taskEvaluation?type=' + type + '&taskid=' + deliverManuscriptList[index].task_id + '&workid=' + deliverManuscriptList[index].id + '&avatar=' + deliverManuscriptList[index].avatar + '&title=' + deliverManuscriptList[index].nickname,
      })
    }else {
      for (var i = 0; i < taskContributeList.workList.length; i++) {
        if (taskContributeList.workList[i].status == 1) {
          workid = taskContributeList.workList[i].id
        }
      }
      wx.navigateTo({
        url: '/taskPage/pages/taskEvaluation/taskEvaluation?type=' + type + '&taskid=' + id + '&workid=' + workid + '&avatar=' + taskDetail.to_comment_avatar + '&title=' + taskDetail.to_comment_name,
      })
    }
  },
  // 游客模式其登录
  loginBtn:function(){
    wx.navigateTo({
      url: '/userPage/pages/login/login',
    })
  },


  photoClose(){
    this.setData({
      photoSelectShow:false
    })
  },

  // 附件下载
  wxdown:function(event){
    var { down_url, annextype} = event.currentTarget.dataset;
    console.log(down_url, annextype)
    let _that = this;
    if (annextype != 'jpg' && annextype != 'png' && annextype != 'jpeg' && annextype != 'gif'){
      if (annextype != 'zip' && annextype != 'rar'){
        wx.downloadFile({
          url: down_url,
          success: function (res) {
            const tempFilePath = res.tempFilePath;
            // 保存文件
            wx.saveFile({
              tempFilePath,
              success: function (res) {
                const savedFilePath = res.savedFilePath;
                // 打开文件
                wx.openDocument({
                  filePath: savedFilePath,
                  showMenu:true,
                  success: function (res) {
                    console.log('打开文档成功')
                  },
                });
              },
              fail: function (err) {
                console.log('保存失败：', err)
              }
            });
          },
          fail: function (err) {
            console.log('下载失败：', err);
          },
        });
      }else{
        wx.showToast({
          title: '暂不支持该文件类型',
          icon: "none",
          duration: 2000
        })
      }
      return false;
    }else{

      this.setData({
        photoSelectShow:true,
        photoUrl:down_url,
      })
    }
   },


  photoSelect(event){
    const {value}=event.detail
    console.log(event,'event------')
    let down_url=this.data.photoUrl
    if(value===1){
      //下载
      this.getPhoto(down_url)
    }else {
      //预览
      wx.previewImage({
        current: down_url, // 当前显示图片的http链接
        urls:[
          down_url
        ]
      })
    }
  },




  //图片下载
  getPhoto(down_url){
    let _that = this;
    wx.showToast({
      icon: 'loading',
      title: '正在保存图片',
      duration: 1000
    })
    //判断用户是否授权"保存到相册"
    wx.getSetting({
      success(res) {
        //没有权限，发起授权
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {//用户允许授权，保存图片到相册
              _that.savePhoto(down_url);
            },
            fail() {//用户点击拒绝授权，跳转到设置页，引导用户授权
              wx.openSetting({
                success() {
                  wx.authorize({
                    scope: 'scope.writePhotosAlbum',
                    success() {
                      _that.savePhoto(down_url);
                    }
                  })
                }
              })
            }
          })
        } else {//用户已授权，保存到相册
          _that.savePhoto(down_url);
        }
      }
    })
  },

  //保存图片到相册，提示保存成功
   savePhoto(down_url) {
    wx.downloadFile({
     url: down_url,
     success: function (res) {
      wx.saveImageToPhotosAlbum({
       filePath: res.tempFilePath,
       success(res) {
        wx.showToast({
         title: '保存成功',
         icon: "success",
         duration: 1000
        })
       }
      })
     }
    })

    /*wx.downloadFile({
      url: down_url,
      success: function (res) {
        var filePath = res.tempFilePath;
        console.log(res)
        //页面显示加载动画
        wx.saveFile({
          tempFilePath: filePath,
          success: function (res) {
            console.log(res);
            console.log('下载成功')
          },
          fail:function(res){
            console.log('下载失败')
            console.log(res)
          },
          complete: function(res) {
            console.log(res)
          }
        })
      }
    })*/


  },


  orderDetail(){
    let {id,taskDetail} = this.data
    let type = taskDetail.task_type
    if(type == 'xuanshang'){
      wx.navigateTo({
        url: '/taskPage/pages/xsOrderDetail/xsOrderDetail?id=' + id,
      })
    }else{
      wx.navigateTo({
        url: '/taskPage/pages/zbOrderDetail/zbOrderDetail?id=' + id,
      })
    }

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },



  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
